package com.hengpeng.itfin.job;

import java.util.Date;
import java.util.List;

import com.hengpeng.common.cis.ComponentContextLoader;
import com.hengpeng.common.scheduling.AbstractJob;
import com.hengpeng.common.scheduling.ScheduleConfig;
import com.hengpeng.itfin.service.ServiceFactory;
import com.hengpeng.itfin.tools.PoolServer;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.persist.RewardRedpacket;

/**
 * 红包过期检查作业
 * 
 * @author weiyuan
 */
public class RedPacketCheckJob extends AbstractJob {

    private ServiceFactory serviceFactory = ComponentContextLoader.getBean(ServiceFactory.class);

    private static final int fetchsize = 100;// 一次性批处理数量

    private static final int poolSize = 30;// 定义线程池大小

    @Override
    public void exec(boolean isTimeout, ScheduleConfig config) {
        log.info("红包过期检查作业开始");
        List<RewardRedpacket> canUserList = serviceFactory.getDaoFactory().getRedPacketDao()
                .findRedPacketByStatus(RewardRedPacketStatus.CANUSE, fetchsize);
        if (canUserList != null && canUserList.size() > 0) {
            PoolServer poolServer = new PoolServer(poolSize);
            for (final RewardRedpacket red : canUserList) {
                poolServer.executeTask(new Runnable() {
                    public void run() {
                        if (red.getEndtime() != null && System.currentTimeMillis() > red.getEndtime().getTime()) {
                            int i = serviceFactory
                                    .getDaoFactory()
                                    .getRedPacketDao()
                                    .updateStatus(red.getId(), RewardRedPacketStatus.CANUSE, RewardRedPacketStatus.OUTDATE,
                                            new Date());
                            if (i > 0) {
                                log.info("用户[id=" + red.getUserId() + "],红包[id=" + red.getId() + "]已过期");
                            }
                        }
                    }
                });
            }
            poolServer.endServer();
        }
        log.info("红包过期检查作业结束");
    }
}